package com.smile.frame.seckill.service;

import com.smile.frame.seckill.mapper.PaymentMapper;
import com.smile.frame.seckill.mapper.SecondKillMapper;
import com.smile.frame.seckill.mapper.SuccessKillMapper;
import com.smile.frame.seckill.model.Payment;
import com.smile.frame.seckill.model.SecondKill;
import com.smile.frame.seckill.model.SuccessKill;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author LGC
 * @date 2025/1/21
 */
@Slf4j
@Service
public class SecondKillServiceImpl implements SecondKillService {
    @Resource
    private SecondKillMapper secondKillMapper;
    @Resource
    private SuccessKillMapper successKillMapper;
    @Resource
    private PaymentMapper paymentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startSecondKillByLock(long skgId, long userId) {
        // 校验库存
        SecondKill secondKill = secondKillMapper.selectById(skgId);
        Integer number = secondKill.getNumber();
        if (number > 0) {
            // 扣库存
            secondKill.setNumber(number - 1);
            secondKillMapper.updateById(secondKill);
            // 创建订单
            SuccessKill killed = new SuccessKill();
            killed.setSkillId(skgId);
            killed.setUserId(userId);
            killed.setState(0);
            killed.setCreateTime(new Date());
            successKillMapper.insert(killed);

            // 模拟支付
            Payment payment = new Payment();
            payment.setSkillId(skgId);
            payment.setUserId(userId);
            payment.setMoney(new BigDecimal("99.99"));
            payment.setState(1);
            payment.setCreateTime(new Date());
            paymentMapper.insert(payment);
            return true;
        }
        return false;
    }
}
